<template>
  <div class="add-border" style="display: flex;" v-loading="loading">
    <div class="border-normal" style="width: 230px; height: 600px; overflow-y:auto;">
      <div
        class="border-select"
        style="display: flex;"
        v-for="(s, i) in session"
        :key="i"
        :ref="'session' + i"
        :class="s.isSelected == 1 ? 'div-back1' : 'div-back0'"
      >
        <div
          style="height: 50px; width: 200px; margin-top: 2px; margin-bottom: 2px; margin-left: 2px; cursor:pointer;"
          @click="visitSessionContent(s)"
        >
          <div style="height: 48px; margin: auto; display: flex; float: left;">
            <el-image
              style="width: 45px; height: 45px; border-radius: 40px; margin: auto; border: 1px solid #000000; background-color: #ffffff;"
              fit="contain"
              :src="s.targetIcon"
            ></el-image>
          </div>
          <div style="height: 48px; margin: auto; display: flex; float: left;">
            <span style="margin: auto;">{{s.targetName}}</span>
          </div>
        </div>
      </div>
    </div>

    <MessageSession ref="messageSession" @updateSession="updateSession" />
  </div>
</template>

<script>
import MessageSession from "@/components/UserCenter/MessageSession";

export default {
  name: "Message",
  data() {
    return {
      loading: true,
      session: [],
    };
  },
  components: {
    MessageSession,
  },
  methods: {
    initMessage() {
      var url = process.env.URL_HEAD + "/touser/user/page/init/message";

      this.$http.get(url, { withCredentials: true }).then(
        (response) => {
          var send = [];
          var receive = [];
          var target = [];

          if (response.data.send != null) send = response.data.send.list;
          if (response.data.receive != null)
            receive = response.data.receive.list;

          if (response.data.status == "ok") {
            // console.log("send:");
            // console.log(send);
            // console.log("receive:");
            // console.log(receive);

            this.initSession(send, receive);

            console.log("initMessage ok");
          } else {
            console.log("no login");
          }

          this.loading = false;
        },
        (response) => {
          console.log("initMessage fail");

          this.loading = false;
          this.$message.error("加载失败，请刷新");
        }
      );
    },
    initSession(send, receive) {
      var session = [];

      //处理我发出去的
      for (var i = 0; i < send.length; i++) {
        var index = -1;

        for (var j = 0; j < session.length; j++) {
          if (
            session[j].targetType == send[i].receiveType &&
            session[j].targetId == send[i].receiveId
          ) {
            index = j;
            break;
          }
        }

        if (index == -1) {
          session.push({
            targetType: send[i].receiveType,
            targetId: send[i].receiveId,
            targetName: "未知用户",
            targetIcon: "",
            isSelected: 0,
            userId: send[i].sendId,
            content: [],
            maxMessageId: -1,
          });
          index = session.length - 1;
        }

        session[index].maxMessageId = Math.max(
          session[index].maxMessageId,
          send[i].messageId
        );
        session[index].content.push({
          messageId: send[i].messageId,
          isSend: 1,
          content: send[i].content,
        });
      }

      //处理我收到的
      for (var i = 0; i < receive.length; i++) {
        var index = -1;

        for (var j = 0; j < session.length; j++) {
          if (
            session[j].targetType == receive[i].sendType &&
            session[j].targetId == receive[i].sendId
          ) {
            index = j;
            break;
          }
        }

        if (index == -1) {
          session.push({
            targetType: receive[i].sendType,
            targetId: receive[i].sendId,
            targetName: "未知用户",
            targetIcon: "",
            isSelected: 0,
            userId: receive[i].receiveId,
            content: [],
            maxMessageId: -1,
          });
          index = session.length - 1;
        }

        session[index].maxMessageId = Math.max(
          session[index].maxMessageId,
          receive[i].messageId
        );
        session[index].content.push({
          messageId: receive[i].messageId,
          isSend: 0,
          content: receive[i].content,
        });
      }

      //session内消息排序
      for (var i = 0; i < session.length; i++) {
        session[i].content.sort(function (a, b) {
          return a.messageId - b.messageId;
        });
      }
      //session排序
      session.sort(function (a, b) {
        return b.maxMessageId - a.maxMessageId;
      });
      //   console.log(session);
      this.session = session;

      //请求会话对象的名称和头像
      for (var i = 0; i < session.length; i++) {
        this.getTargetInfo(session[i].targetType, session[i].targetId);
      }

      console.log(this.$refs);
    },
    getTargetInfo(targetType, targetId) {
      if (targetType == "store") {
        var url = process.env.URL_HEAD + "/store/store/info/" + targetId;

        this.$http.get(url).then(
          (response) => {
            var store = response.data.store;
            var session = JSON.parse(JSON.stringify(this.session));

            if (store != null) {
              for (var i = 0; i < session.length; i++) {
                if (
                  session[i].targetType == targetType &&
                  session[i].targetId == targetId
                ) {
                  session[i].targetName = store.storeName;
                  session[i].targetIcon = store.storeIcon;
                }
              }
            }

            this.session = session;
            // console.log(this.session);
            // console.log("getTargetInfo ok");
          },
          (response) => {
            // console.log("getTargetInfo fail");
          }
        );
      }
    },
    visitSessionContent(session) {
      var sessions = JSON.parse(JSON.stringify(this.session));

      for (var i = 0; i < sessions.length; i++) {
        sessions[i].isSelected = 0;

        if (
          sessions[i].targetType == session.targetType &&
          sessions[i].targetId == session.targetId
        ) {
          sessions[i].isSelected = 1;
        }
      }

      this.session = sessions;
      this.$refs.messageSession.init(session);
    },
    updateSession(targetType, targetId, isSend, content) {
      var session = JSON.parse(JSON.stringify(this.session));

      for (var i = 0; i < session.length; i++) {
        if (
          session[i].targetType == targetType &&
          session[i].targetId == targetId
        ) {
          session[i].content.push({ isSend: isSend, content: content });
          this.session = session;

          this.$refs.messageSession.init(session[i]);

          break;
        }
      }
    },
  },
  created() {
    this.initMessage();
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.add-border {
  border: 1px solid #ffffff;
}
.border-normal {
  border: 1px solid #bbbbbb;
}
.border-select {
  border: 1px solid #bbbbbb;
}
.border-select:hover {
  border: 1px solid #ff0000;
}

.div-back0 {
  background-color: #ffffff;
}
.div-back1 {
  background-color: #b0dfdf;
}
</style>
